/**
 * @file hybrid_mode_thread.c
 * @brief 混合模式线程实现 - 模式7，结合模拟数据和三摄像头功能
 * @version 1.0
 * @date 2025-06-07
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>
#include <time.h>
#include <sys/stat.h>

#include "hybrid_mode_thread.h"
#include "thread_utils.h"
#include "system_utils.h"
#include "debug_images.h"
#include "simulation.h"
#include "common_defs.h"
#include "camera_utils.h"
#include "image_process.h"
#include "app_control.h"
#include "camera_time_sync.h"

// 图像处理函数声明
#ifdef HAVE_OPENCV
extern bool opencv_load_image(const char* filename, unsigned char** data, int* width, int* height, int* channels);
extern bool opencv_save_image(const unsigned char* image_data, int width, int height, int channels, 
                      const char* filename, int quality);
extern bool opencv_annotate_image(unsigned char* image_data, int width, int height, int channels,
                          const char* timestamp,
                          float temperature, float humidity,
                          float wind_speed, float wind_direction,
                          float tension1, float tension2);
extern bool opencv_add_custom_text(unsigned char* image_data, int width, int height, int channels,
                          const char* text);
#endif

// 全局变量定义
pthread_t g_hybrid_thread = 0;
volatile HybridThreadState g_hybrid_thread_state = HYBRID_THREAD_IDLE;
volatile bool g_hybrid_thread_exit = false;

// 互斥锁，用于保护线程状态
static pthread_mutex_t g_hybrid_thread_mutex = PTHREAD_MUTEX_INITIALIZER;

// 摄像头认证信息
static CameraAuthInfo g_camera_auth_info[3];

// 图像缓冲区
typedef struct {
    unsigned char* data;
    int width;
    int height;
    int channels;
    bool valid;
} ImageBuffer;

static ImageBuffer g_cam_400w_image = {0};
static ImageBuffer g_cam_800w_left_image = {0};
static ImageBuffer g_cam_800w_right_image = {0};

// 添加外部变量声明
extern AppConfig g_config;

// 线程函数前向声明
static void* hybrid_mode_thread_func(void *arg);

// 声明 ensure_directory_exists 函数
static int ensure_directory_exists(const char *directory);

/**
 * @brief 设置线程状态
 * 
 * @param state 新状态
 */
static void set_thread_state(HybridThreadState state) {
    pthread_mutex_lock(&g_hybrid_thread_mutex);
    g_hybrid_thread_state = state;
    pthread_mutex_unlock(&g_hybrid_thread_mutex);
}

/**
 * @brief 初始化图像缓冲区
 * 
 * @param buffer 图像缓冲区
 * @param width 宽度
 * @param height 高度
 * @param channels 通道数
 * @return int 成功返回0，失败返回非0
 */
static int init_image_buffer(ImageBuffer* buffer, int width, int height, int channels) {
    if (buffer->data) {
        free(buffer->data);
        buffer->data = NULL;
    }
    
    buffer->data = (unsigned char*)malloc(width * height * channels);
    if (!buffer->data) {
        return -1;
    }
    
    buffer->width = width;
    buffer->height = height;
    buffer->channels = channels;
    buffer->valid = false;
    
    return 0;
}

/**
 * @brief 清理图像缓冲区
 * 
 * @param buffer 图像缓冲区
 */
static void cleanup_image_buffer(ImageBuffer* buffer) {
    if (buffer->data) {
        free(buffer->data);
        buffer->data = NULL;
    }
    
    buffer->width = 0;
    buffer->height = 0;
    buffer->channels = 0;
    buffer->valid = false;
}

/**
 * @brief 安全地复制字符串，如果源字符串过长则截断并记录警告
 * 
 * @param dest 目标字符串缓冲区
 * @param dest_size 目标缓冲区大小
 * @param src 源字符串
 * @param field_name 字段名称(用于日志输出)
 */
static void safe_string_copy(char *dest, size_t dest_size, const char *src, const char *field_name) {
    if (!dest || !src || dest_size == 0) {
        return;
    }
    
    // 检查源字符串长度
    size_t src_len = strlen(src);
    
    // 复制字符串，确保字符串终止
    size_t copy_len = (src_len < dest_size - 1) ? src_len : (dest_size - 1);
    memcpy(dest, src, copy_len);
    dest[copy_len] = '\0';
    
    // 如果源字符串被截断，记录警告
    if (src_len >= dest_size) {
        log_message(LOG_LEVEL_WARNING, 
                   "字符串过长，已截断: %s (长度: %zu, 限制: %zu)", 
                   field_name, src_len, dest_size - 1);
    }
}

/**
 * @brief 从摄像头捕获图像
 * 
 * @param camera_ip 摄像头IP
 * @param username 用户名
 * @param password 密码
 * @param buffer 图像缓冲区
 * @return int 成功返回0，失败返回非0
 */
static int capture_image_from_camera(const char* camera_ip, const char* username, 
                                    const char* password, ImageBuffer* buffer) {
    if (!buffer->data) {
        log_message(LOG_LEVEL_ERROR, "图像缓冲区未初始化");
        return -1;
    }
    
    // 创建摄像头认证信息
    CameraAuthInfo auth_info;
    strncpy(auth_info.ip, camera_ip, sizeof(auth_info.ip) - 1);
    auth_info.ip[sizeof(auth_info.ip) - 1] = '\0';
    strncpy(auth_info.username, username, sizeof(auth_info.username) - 1);
    auth_info.username[sizeof(auth_info.username) - 1] = '\0';
    strncpy(auth_info.password, password, sizeof(auth_info.password) - 1);
    auth_info.password[sizeof(auth_info.password) - 1] = '\0';
    
    // 根据IP地址判断摄像头类型
    if (strstr(camera_ip, "192.168.1.60") != NULL) {
        auth_info.type = CAMERA_TYPE_400W; // 400W摄像头
        log_message(LOG_LEVEL_DEBUG, "检测到400W摄像头: %s", camera_ip);
    } else {
        auth_info.type = CAMERA_TYPE_800W; // 800W摄像头
        log_message(LOG_LEVEL_DEBUG, "检测到800W摄像头: %s", camera_ip);
    }
    
    // 创建临时目录
    const char* temp_dir = "temp_capture";
    if (ensure_directory_exists(temp_dir) != 0) {
        log_message(LOG_LEVEL_ERROR, "无法创建临时目录: %s", temp_dir);
        return -1;
    }
    
    // 创建唯一的临时文件名
    char temp_filename[256];
    snprintf(temp_filename, sizeof(temp_filename), "temp_img_%lu.jpg", (unsigned long)time(NULL));
    
    log_message(LOG_LEVEL_DEBUG, "尝试从摄像头 %s 捕获图像，保存到 %s/%s", camera_ip, temp_dir, temp_filename);
    
    // 捕获图像到文件
    int ret = capture_single_camera_image(
        auth_info.ip, 
        auth_info.username, 
        auth_info.password,
        auth_info.type, 
        temp_dir, 
        temp_filename
    );
    
    if (ret != 0) {
        log_message(LOG_LEVEL_ERROR, "捕获图像到文件失败 (返回值:%d): %s/%s", ret, temp_dir, temp_filename);
        buffer->valid = false;
        return -1;
    }
    
    // 构建完整文件路径
    char full_path[512];
    snprintf(full_path, sizeof(full_path), "%s/%s", temp_dir, temp_filename);
    
    // 检查文件是否存在
    struct stat file_stat;
    if (stat(full_path, &file_stat) != 0) {
        log_message(LOG_LEVEL_ERROR, "捕获的图像文件不存在: %s", full_path);
        buffer->valid = false;
        return -1;
    }
    
    log_message(LOG_LEVEL_DEBUG, "成功捕获图像，文件大小: %ld 字节", (long)file_stat.st_size);
    
    // 从文件加载图像到缓冲区
#ifdef HAVE_OPENCV
    bool load_success = opencv_load_image(full_path, &buffer->data, &buffer->width, &buffer->height, &buffer->channels);
    if (!load_success) {
        log_message(LOG_LEVEL_ERROR, "从文件加载图像失败: %s", full_path);
        remove(full_path); // 删除临时文件
        buffer->valid = false;
        return -1;
    }
    
    log_message(LOG_LEVEL_DEBUG, "成功加载图像: %dx%d, %d通道", buffer->width, buffer->height, buffer->channels);
#else
    log_message(LOG_LEVEL_ERROR, "未启用OpenCV支持，无法加载图像");
    remove(full_path); // 删除临时文件
    buffer->valid = false;
    return -1;
#endif
    
    // 删除临时文件
    if (remove(full_path) != 0) {
        log_message(LOG_LEVEL_WARNING, "删除临时文件失败: %s (errno: %d)", full_path, errno);
    }
    
    buffer->valid = true;
    log_message(LOG_LEVEL_DEBUG, "成功从摄像头 %s 捕获图像", camera_ip);
    return 0;
}

/**
 * @brief 在图像上标注模拟数据
 * 
 * @param image 图像数据
 * @param width 图像宽度
 * @param height 图像高度
 * @param channels 通道数
 * @param equivalent_data 是否使用等效线缆数据(true)或真实线缆数据(false)
 * @return int 成功返回0，失败返回非0
 */
static int annotate_with_simulation_data(unsigned char* image, int width, int height, 
                                        int channels, bool equivalent_data) {
#ifdef HAVE_OPENCV
    // 获取当前系统时间
    char time_str[32];
    time_t now = time(NULL);
    struct tm tm_info;
    
#ifdef _WIN32
    localtime_s(&tm_info, &now);
#else
    localtime_r(&now, &tm_info);
#endif
    
    strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", &tm_info);
    
    // 获取模拟数据
    SensorData sensor_data = {0};
    get_simulation_sensor_data(&sensor_data);
    const SimulationData* sim_data = get_simulation_data();
    
    // 准备要标注的文本
    char custom_text[128];
    
    if (equivalent_data) {
        // 等效线缆数据
        snprintf(custom_text, sizeof(custom_text), 
                "等效线缆覆冰厚度: %.2fmm", 
                sim_data->equivalent_ice_thickness);
    } else {
        // 真实线缆数据
        snprintf(custom_text, sizeof(custom_text), 
                "真实线缆覆冰厚度: %.2fmm", 
                sim_data->real_ice_thickness);
    }
    
    // 调用OpenCV函数添加标注
    opencv_annotate_image(
        image, width, height, channels,
        time_str,
        sensor_data.temperature,
        sensor_data.humidity,
        sensor_data.wind_speed,
        sensor_data.wind_direction,
        sensor_data.tension1,
        sensor_data.tension2
    );
    
    // 添加自定义文本
    opencv_add_custom_text(image, width, height, channels, custom_text);
    
    return 0;
#else
    log_message(LOG_LEVEL_WARNING, "未启用OpenCV支持，无法在图像上添加标注");
    return -1;
#endif
}

/**
 * @brief 保存带有标注的图像
 * 
 * @param buffer 图像缓冲区
 * @param prefix 文件名前缀
 * @return int 成功返回0，失败返回非0
 */
static int save_annotated_image(ImageBuffer* buffer, const char* prefix) {
    if (!buffer->valid || !buffer->data) {
        log_message(LOG_LEVEL_ERROR, "无效的图像缓冲区");
        return -1;
    }
    
    // 获取时间字符串用于文件名
    char time_str[32];
    time_t now = time(NULL);
    struct tm tm_info;
    
#ifdef _WIN32
    localtime_s(&tm_info, &now);
#else
    localtime_r(&now, &tm_info);
#endif
    
    strftime(time_str, sizeof(time_str), "%Y%m%d_%H%M%S", &tm_info);
    
    // 构建目录路径和文件名
    const char* save_dir = "picture_docu";
    char filename[512];
    snprintf(filename, sizeof(filename), "%s/%s_%s.jpg", save_dir, prefix, time_str);
    
    // 确保目录存在
    if (ensure_directory_exists(save_dir) != 0) {
        log_message(LOG_LEVEL_ERROR, "无法创建保存目录: %s", save_dir);
        return -1;
    }
    
#ifdef HAVE_OPENCV
    // 保存图像
    log_message(LOG_LEVEL_DEBUG, "正在保存图像 %s (%dx%d, %d通道)...", 
                filename, buffer->width, buffer->height, buffer->channels);
                
    bool save_success = opencv_save_image(
        buffer->data,
        buffer->width,
        buffer->height,
        buffer->channels,
        filename, 95);  // 使用较高的质量
    
    if (save_success) {
        log_message(LOG_LEVEL_INFO, "已保存图像: %s", filename);
        
        // 验证文件是否确实创建
        struct stat file_stat;
        if (stat(filename, &file_stat) == 0) {
            log_message(LOG_LEVEL_DEBUG, "图像文件大小: %ld 字节", (long)file_stat.st_size);
            return 0;
        } else {
            log_message(LOG_LEVEL_ERROR, "已保存图像但文件不存在: %s (errno: %d)", filename, errno);
            return -1;
        }
    } else {
        log_message(LOG_LEVEL_ERROR, "保存图像失败: %s", filename);
        return -1;
    }
#else
    log_message(LOG_LEVEL_ERROR, "未启用OpenCV支持，无法保存图像");
    return -1;
#endif
}

/**
 * @brief 启动混合模式线程
 * 
 * @return int 成功返回0，失败返回非0
 */
int start_hybrid_mode_thread(void) {
    // 检查线程是否已经在运行
    if (g_hybrid_thread_state == HYBRID_THREAD_RUNNING) {
        log_message(LOG_LEVEL_WARNING, "混合模式线程已经在运行");
        return 0;
    }
    
    // 重置退出标志
    g_hybrid_thread_exit = false;
    
    // 设置线程状态为空闲
    set_thread_state(HYBRID_THREAD_IDLE);
    
    // 创建线程
    int ret = create_thread(&g_hybrid_thread, hybrid_mode_thread_func, NULL, "混合模式");
    if (ret != 0) {
        log_message(LOG_LEVEL_ERROR, "创建混合模式线程失败: %d", ret);
        return -1;
    }
    
    log_message(LOG_LEVEL_INFO, "混合模式线程已启动");
    
    return 0;
}

/**
 * @brief 停止混合模式线程
 * 
 * @return int 成功返回0，失败返回非0
 */
int stop_hybrid_mode_thread(void) {
    // 检查线程是否在运行
    if (g_hybrid_thread_state != HYBRID_THREAD_RUNNING && g_hybrid_thread == 0) {
        log_message(LOG_LEVEL_WARNING, "混合模式线程未在运行");
        return 0;
    }
    
    // 设置退出标志
    g_hybrid_thread_exit = true;
    
    // 设置线程状态为正在停止
    set_thread_state(HYBRID_THREAD_STOPPING);
    
    log_message(LOG_LEVEL_INFO, "正在停止混合模式线程...");
    
    // 等待线程结束
    int ret = wait_hybrid_mode_thread(5000);  // 等待最多5秒
    if (ret != 0) {
        log_message(LOG_LEVEL_WARNING, "等待混合模式线程结束超时");
        
        // 强制取消线程
        if (g_hybrid_thread != 0) {
            cancel_thread(g_hybrid_thread);
            join_thread(g_hybrid_thread, NULL);
            g_hybrid_thread = 0;
        }
    }
    
    set_thread_state(HYBRID_THREAD_STOPPED);
    log_message(LOG_LEVEL_INFO, "混合模式线程已停止");
    
    return 0;
}

/**
 * @brief 获取混合模式线程状态
 * 
 * @return HybridThreadState 线程状态
 */
HybridThreadState get_hybrid_mode_thread_state(void) {
    HybridThreadState state;
    
    pthread_mutex_lock(&g_hybrid_thread_mutex);
    state = g_hybrid_thread_state;
    pthread_mutex_unlock(&g_hybrid_thread_mutex);
    
    return state;
}

/**
 * @brief 等待混合模式线程结束
 * 
 * @param timeout_ms 超时时间(毫秒)，-1表示无限等待
 * @return int 成功返回0，超时返回1，失败返回-1
 */
int wait_hybrid_mode_thread(int timeout_ms) {
    // 检查线程是否存在
    if (g_hybrid_thread == 0) {
        return 0;  // 线程不存在，视为成功
    }
    
    if (timeout_ms < 0) {
        // 无限等待
        return join_thread(g_hybrid_thread, NULL);
    } else {
        // 有限等待
        time_t start_time = time(NULL);
        int elapsed_ms = 0;
        
        while (elapsed_ms < timeout_ms) {
            // 检查线程状态
            if (get_hybrid_mode_thread_state() == HYBRID_THREAD_STOPPED) {
                join_thread(g_hybrid_thread, NULL);
                g_hybrid_thread = 0;
                return 0;
            }
            
            // 休眠100毫秒
            thread_sleep(100);
            
            // 计算已经过的时间
            elapsed_ms = (int)((time(NULL) - start_time) * 1000);
        }
        
        // 超时
        return 1;
    }
}

/**
 * @brief 确保目录存在，如果不存在则创建
 * 
 * @param directory 目录路径
 * @return int 成功返回0，失败返回非0
 */
static int ensure_directory_exists(const char *directory) {
    struct stat st = {0};
    
#ifdef _WIN32
    // Windows平台
    if (stat(directory, &st) == -1) {
        if (mkdir(directory) != 0) {
            log_message(LOG_LEVEL_ERROR, "创建目录失败: %s", directory);
            return -1;
        }
    }
#else
    // Linux/Unix平台
    if (stat(directory, &st) == -1) {
        if (mkdir(directory, 0755) != 0) {
            log_message(LOG_LEVEL_ERROR, "创建目录失败: %s", directory);
            return -1;
        }
    }
#endif
    
    return 0;
}

/**
 * @brief 混合模式线程函数
 * 
 * @param arg 线程参数
 * @return void* 线程返回值
 */
static void* hybrid_mode_thread_func(void *arg) {
    // 设置线程为可取消状态
    set_thread_cancel_state(1);
    set_thread_cancel_type(0);
    
    log_message(LOG_LEVEL_INFO, "混合模式线程已启动, 每10秒采集一次");
    
    // 设置线程状态为运行中
    set_thread_state(HYBRID_THREAD_RUNNING);
    
    // 初始化摄像头认证信息
    memset(g_camera_auth_info, 0, sizeof(g_camera_auth_info));
    
    // 配置400W摄像头
    safe_string_copy(g_camera_auth_info[0].ip, sizeof(g_camera_auth_info[0].ip), 
                    g_config.visual_config.camera_url, "400W摄像头IP");
    safe_string_copy(g_camera_auth_info[0].username, sizeof(g_camera_auth_info[0].username), 
                    g_config.visual_config.username, "400W摄像头用户名");
    safe_string_copy(g_camera_auth_info[0].password, sizeof(g_camera_auth_info[0].password), 
                    g_config.visual_config.password, "400W摄像头密码");
    
    // 配置左侧800W摄像头
    safe_string_copy(g_camera_auth_info[1].ip, sizeof(g_camera_auth_info[1].ip), 
                    g_config.stereo_config.left_camera_url, "左800W摄像头IP");
    safe_string_copy(g_camera_auth_info[1].username, sizeof(g_camera_auth_info[1].username), 
                    g_config.stereo_config.username, "左800W摄像头用户名");
    safe_string_copy(g_camera_auth_info[1].password, sizeof(g_camera_auth_info[1].password), 
                    g_config.stereo_config.password, "左800W摄像头密码");
    
    // 配置右侧800W摄像头
    safe_string_copy(g_camera_auth_info[2].ip, sizeof(g_camera_auth_info[2].ip), 
                    g_config.stereo_config.right_camera_url, "右800W摄像头IP");
    safe_string_copy(g_camera_auth_info[2].username, sizeof(g_camera_auth_info[2].username), 
                    g_config.stereo_config.username, "右800W摄像头用户名");
    safe_string_copy(g_camera_auth_info[2].password, sizeof(g_camera_auth_info[2].password), 
                    g_config.stereo_config.password, "右800W摄像头密码");
    
    // 初始化图像缓冲区
    if (init_image_buffer(&g_cam_400w_image, 1920, 1080, 3) != 0 ||
        init_image_buffer(&g_cam_800w_left_image, 3264, 2448, 3) != 0 ||
        init_image_buffer(&g_cam_800w_right_image, 3264, 2448, 3) != 0) {
        log_message(LOG_LEVEL_ERROR, "初始化图像缓冲区失败");
        set_thread_state(HYBRID_THREAD_ERROR);
        return (void*)(intptr_t)-1;
    }
    
    // 初始化CURL库
    if (init_curl_library() != 0) {
        log_message(LOG_LEVEL_ERROR, "初始化CURL库失败");
        
        cleanup_image_buffer(&g_cam_400w_image);
        cleanup_image_buffer(&g_cam_800w_left_image);
        cleanup_image_buffer(&g_cam_800w_right_image);
        
        set_thread_state(HYBRID_THREAD_ERROR);
        return (void*)(intptr_t)-1;
    }
    
    // 初始化模拟器
    if (init_simulation() != 0) {
        log_message(LOG_LEVEL_ERROR, "初始化模拟器失败");
        
        cleanup_curl_library();
        cleanup_image_buffer(&g_cam_400w_image);
        cleanup_image_buffer(&g_cam_800w_left_image);
        cleanup_image_buffer(&g_cam_800w_right_image);
        
        set_thread_state(HYBRID_THREAD_ERROR);
        return (void*)(intptr_t)-1;
    }
    
    // 主循环 - 每10秒运行一次
    const int loop_interval_ms = 10000; // 10秒
    uint64_t last_run_time = 0;
    
    while (!g_hybrid_thread_exit) {
        uint64_t current_time = get_timestamp_ms();
        
        // 检查是否该执行操作
        if (current_time - last_run_time >= loop_interval_ms) {
            // 更新最后运行时间
            last_run_time = current_time;
            
            // 1. 生成模拟数据 (与模式5相同)
            update_simulation_environment();
            update_simulation_ice_thickness();
            
            const SimulationData* sim_data = get_simulation_data();
            
            log_message(LOG_LEVEL_INFO, "生成模拟数据: 等效线缆厚度=%.2fmm, 真实线缆厚度=%.2fmm", 
                       sim_data->equivalent_ice_thickness, 
                       sim_data->real_ice_thickness);
            
            // 2. 从三个摄像头获取图像 (与模式10相同)
            int success_count = 0;
            
            // 捕获400W摄像头图像
            if (capture_image_from_camera(
                    g_camera_auth_info[0].ip, 
                    g_camera_auth_info[0].username, 
                    g_camera_auth_info[0].password, 
                    &g_cam_400w_image) == 0) {
                
                // 标注等效线缆模拟数据
                annotate_with_simulation_data(
                    g_cam_400w_image.data, 
                    g_cam_400w_image.width, 
                    g_cam_400w_image.height, 
                    g_cam_400w_image.channels, 
                    true);  // 使用等效线缆数据
                
                // 保存图像
                if (save_annotated_image(&g_cam_400w_image, "hybrid_400w") == 0) {
                    success_count++;
                }
            } else {
                log_message(LOG_LEVEL_ERROR, "捕获400W摄像头图像失败");
            }
            
            // 捕获左侧800W摄像头图像
            if (capture_image_from_camera(
                    g_camera_auth_info[1].ip, 
                    g_camera_auth_info[1].username, 
                    g_camera_auth_info[1].password, 
                    &g_cam_800w_left_image) == 0) {
                
                // 标注真实线缆模拟数据
                annotate_with_simulation_data(
                    g_cam_800w_left_image.data, 
                    g_cam_800w_left_image.width, 
                    g_cam_800w_left_image.height, 
                    g_cam_800w_left_image.channels, 
                    false);  // 使用真实线缆数据
                
                // 保存图像
                if (save_annotated_image(&g_cam_800w_left_image, "hybrid_800w_left") == 0) {
                    success_count++;
                }
            } else {
                log_message(LOG_LEVEL_ERROR, "捕获左侧800W摄像头图像失败");
            }
            
            // 捕获右侧800W摄像头图像
            if (capture_image_from_camera(
                    g_camera_auth_info[2].ip, 
                    g_camera_auth_info[2].username, 
                    g_camera_auth_info[2].password, 
                    &g_cam_800w_right_image) == 0) {
                
                // 标注真实线缆模拟数据
                annotate_with_simulation_data(
                    g_cam_800w_right_image.data, 
                    g_cam_800w_right_image.width, 
                    g_cam_800w_right_image.height, 
                    g_cam_800w_right_image.channels, 
                    false);  // 使用真实线缆数据
                
                // 保存图像
                if (save_annotated_image(&g_cam_800w_right_image, "hybrid_800w_right") == 0) {
                    success_count++;
                }
            } else {
                log_message(LOG_LEVEL_ERROR, "捕获右侧800W摄像头图像失败");
            }
            
            log_message(LOG_LEVEL_INFO, "混合模式: 本次成功捕获并处理 %d/3 个图像", success_count);
        }
        
        // 短暂休眠，防止CPU占用过高
        thread_sleep(1000);  // 休眠1秒
    }
    
    // 清理资源
    cleanup_simulation();
    cleanup_curl_library();
    cleanup_image_buffer(&g_cam_400w_image);
    cleanup_image_buffer(&g_cam_800w_left_image);
    cleanup_image_buffer(&g_cam_800w_right_image);
    
    // 设置线程状态为已停止
    set_thread_state(HYBRID_THREAD_STOPPED);
    log_message(LOG_LEVEL_INFO, "混合模式线程已完成");
    
    return NULL;
} 